﻿using System.Security.Claims;
using AGooday.AgChat.Api.Data;
using AGooday.AgChat.Api.Hubs;
using AGooday.AgChat.Api.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;
using Microsoft.EntityFrameworkCore;

namespace AGooday.AgChat.Api.Controllers
{// Controllers/UsersController.cs
    [ApiController]
    [Route("api/[controller]")]
    [Authorize]
    public class UsersController : ControllerBase
    {
        private readonly ApplicationDbContext _context;
        private readonly IHubContext<ChatHub> _hubContext;

        public UsersController(ApplicationDbContext context)
        {
            _context = context;
        }

        [HttpGet("search")]
        public async Task<IActionResult> SearchUsers(string query)
        {
            var userId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value);

            var users = await _context.Users
                .Where(u => u.Id != userId && (u.Username.Contains(query) || u.Email.Contains(query)))
                .Select(u => new
                {
                    u.Id,
                    u.Username,
                    u.Email,
                    u.Avatar,
                    u.Status,
                    u.LastSeen,
                    IsFriend = _context.Friendships.Any(f =>
                        (f.UserId == userId && f.FriendId == u.Id && f.Status == "accepted") ||
                        (f.UserId == u.Id && f.FriendId == userId && f.Status == "accepted"))
                })
                .ToListAsync();

            return Ok(users);
        }

        [HttpGet("friends")]
        public async Task<IActionResult> GetFriends()
        {
            var userId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value);

            var friends = await _context.Friendships
                .Where(f => f.UserId == userId && f.Status == "accepted")
                .Include(f => f.Friend)
                .Select(f => new
                {
                    f.Friend.Id,
                    f.Friend.Username,
                    f.Friend.Avatar,
                    f.Friend.Status,
                    f.Friend.LastSeen,
                    UnreadCount = _context.Messages.Count(m =>
                        m.SenderId == f.FriendId && m.ReceiverId == userId && !m.IsRead)
                })
                .ToListAsync();

            return Ok(friends);
        }

        [HttpPost("friends/{friendId}")]
        public async Task<IActionResult> AddFriend(int friendId)
        {
            var userId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value);

            if (userId == friendId)
            {
                return BadRequest("Cannot add yourself as a friend");
            }

            var existingFriendship = await _context.Friendships
                .FirstOrDefaultAsync(f =>
                    (f.UserId == userId && f.FriendId == friendId) ||
                    (f.UserId == friendId && f.FriendId == userId));

            if (existingFriendship != null)
            {
                if (existingFriendship.Status == "accepted")
                {
                    return BadRequest("Already friends");
                }

                if (existingFriendship.Status == "pending" && existingFriendship.UserId == userId)
                {
                    return BadRequest("Friend request already sent");
                }

                if (existingFriendship.Status == "pending" && existingFriendship.UserId == friendId)
                {
                    // 对方已经发过申请，现在直接接受
                    existingFriendship.Status = "accepted";
                    // 创建反向记录
                    var reverseFriendship = new Friendship
                    {
                        UserId = userId,
                        FriendId = friendId,
                        Status = "accepted",
                        CreatedAt = DateTime.UtcNow
                    };
                    _context.Friendships.Add(reverseFriendship);
                    await _context.SaveChangesAsync();

                    // 通知对方
                    await _hubContext.Clients.User(friendId.ToString())
                        .SendAsync("FriendRequestAccepted", new
                        {
                            UserId = userId,
                            UserName = User.Identity.Name
                        });

                    return Ok("Friend request accepted");
                }

                if (existingFriendship.Status == "blocked")
                {
                    return BadRequest("Cannot add blocked user");
                }
            }

            var friendship = new Friendship
            {
                UserId = userId,
                FriendId = friendId,
                Status = "pending",
                CreatedAt = DateTime.UtcNow
            };

            _context.Friendships.Add(friendship);
            await _context.SaveChangesAsync();

            // 通知被申请者
            await _hubContext.Clients.User(friendId.ToString())
                .SendAsync("ReceiveFriendRequest", new
                {
                    friendship.Id,
                    SenderId = userId,
                    SenderName = User.Identity.Name,
                    //friendship.VerificationMessage,
                    friendship.CreatedAt
                });

            return Ok("Friend request sent");
        }

        [HttpDelete("friends/{friendId}")]
        public async Task<IActionResult> RemoveFriend(int friendId)
        {
            var userId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value);

            var friendship = await _context.Friendships
                .FirstOrDefaultAsync(f =>
                    (f.UserId == userId && f.FriendId == friendId) ||
                    (f.UserId == friendId && f.FriendId == userId));

            if (friendship == null)
            {
                return NotFound("Friendship not found");
            }

            _context.Friendships.Remove(friendship);
            await _context.SaveChangesAsync();

            return Ok("Friend removed");
        }

        // 获取收到的好友申请列表（待处理）
        [HttpGet("friend-requests")]
        public async Task<IActionResult> GetFriendRequests()
        {
            var userId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value);
            var requests = await _context.Friendships
                .Where(f => f.FriendId == userId && f.Status == "pending")
                .Include(f => f.User)
                .Select(f => new
                {
                    f.Id,
                    //f.VerificationMessage,
                    f.CreatedAt,
                    User = new
                    {
                        f.User.Id,
                        f.User.Username,
                        f.User.Avatar
                    }
                })
                .ToListAsync();

            return Ok(requests);
        }

        // 处理好友申请（接受或拒绝）
        [HttpPost("friend-requests/{friendshipId}/respond")]
        public async Task<IActionResult> RespondToFriendRequest(int friendshipId, [FromBody] RespondToRequestModel model)
        {
            var userId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value);
            var friendship = await _context.Friendships
                .FirstOrDefaultAsync(f => f.Id == friendshipId && f.FriendId == userId && f.Status == "pending");

            if (friendship == null)
            {
                return NotFound("Friend request not found");
            }

            if (model.Accept)
            {
                friendship.Status = "accepted";
                // 同时创建反向的好友关系（如果需要双向记录）
                var reverseFriendship = new Friendship
                {
                    UserId = userId,
                    FriendId = friendship.UserId,
                    Status = "accepted",
                    CreatedAt = DateTime.UtcNow
                };
                _context.Friendships.Add(reverseFriendship);
            }
            else
            {
                friendship.Status = "rejected"; // 或者直接删除，这里我们改为rejected状态
            }

            await _context.SaveChangesAsync();

            // 通知申请者处理结果
            await _hubContext.Clients.User(friendship.UserId.ToString())
                .SendAsync("FriendRequestResponded", new
                {
                    friendship.FriendId,
                    friendship.Status,
                    FriendName = User.Identity.Name // 或者需要查询被申请者的用户名
                });

            return Ok();
        }
    }

    public class RespondToRequestModel
    {
        public bool Accept { get; set; }
    }
}
